<template>
    <div>
        <el-card class="box-card">
            <!-- 卡片顶部的添加按钮 -->
            <el-button type="primary" size="default" icon="Plus" @click="addTrademark">添加品牌</el-button>
            <!-- 表格组件：展示已有的平台数据 -->
            <el-table border style="margin: 10px 0px;" :data="trademarkArr">
                <el-table-column label="序号" type="index" width="80px" align="center"></el-table-column>
                <el-table-column prop="tmName" label="品牌名称"></el-table-column>
                <el-table-column label="品牌LOGO">
                    <template #="{ row }">
                        <img :src="row.logoUrl" style="width: 100px; height: 100px;">
                    </template>
                </el-table-column>
                <el-table-column label="品牌操作">
                    <template #="{ row }">
                        <el-button type="primary" size="small" icon="Edit" @click="updateTrademark(row)"></el-button>
                        <el-popconfirm :title="`您确定要删除${row.tmName}吗？`" width="250px" icon="Delete"
                            @confirm="removeTradeMark(row.id)">
                            <template #reference>
                                <el-button type="primary" size="small" icon="Delete"></el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器组件 -->
            <el-pagination @size-change="changeSize" @current-change="getHasTrademark" v-model:current-page="pageNo"
                v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 9]" :background="true"
                layout="prev, pager, next, jumper,->, sizes,total, " :total="total" />
        </el-card>
        <!-- 对话框组件 -->
        <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '修改品牌' : '添加品牌'">
            <el-form ref="formRef" style="width: 80%;" :model="trademarkParams" :rules="rules">
                <el-form-item prop="tmName" label-width="100px" label="品牌名称">
                    <el-input placeholder="请您输入品牌名称" v-model="trademarkParams.tmName"></el-input>
                </el-form-item>
                <el-form-item prop="logoUrl" label-width="100px" label="品牌LOGO">
                    <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button type="primary" size="default" @click="cancel">取消</el-button>
                <el-button type="primary" size="default" @click="confirm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue';
import { reqTrademark, reqAddOrUpdateTrademark, reqDeleteTrademark } from '@/api/product/trademark/index'
import { ElMessage } from 'element-plus';
let pageNo = ref(1)
let pageSize = ref(3)
let total = ref(0)
// 控制对话框显示与隐藏
let dialogFormVisible = ref(false)
// 存储已有品牌的数据
const trademarkArr = ref([])
// 存储新增品牌收集的数据
let trademarkParams: any = reactive({
    tmName: '',
    logoUrl: ''
})
// 获取form表单实例
let formRef = ref()
onMounted(() => {
    getHasTrademark()
})
// 获取已有品牌的方法
const getHasTrademark = async (pager = 1) => {
    pageNo.value = pager
    let result = await reqTrademark(pageNo.value, pageSize.value)
    if (result.code == 200) {
        total.value = result.data.total
        trademarkArr.value = result.data.records
    }
}
// 分页器下拉菜单的回调
const changeSize = () => {
    getHasTrademark()
}
// 添加品牌按钮的回调
const addTrademark = () => {
    trademarkParams.tmName = ''
    trademarkParams.logoUrl = ''
    trademarkParams.id = 0
    dialogFormVisible.value = true
    nextTick(() => {
        formRef.value.clearValidate(['logoUrl', 'tmName'])
    })
}
// 修改品牌按钮的回调
const updateTrademark = (row: any) => {
    // trademarkParams.tmName = row.tmName
    // trademarkParams.logoUrl = row.logoUrl
    // trademarkParams.id = row.id
    nextTick(() => {
        formRef.value.clearValidate(['logoUrl', 'tmName'])
    })
    Object.assign(trademarkParams, row)
    dialogFormVisible.value = true
}
// 对话框取消按钮回调
const cancel = () => {
    dialogFormVisible.value = false
}
// 对话框确定按钮回调
const confirm = async () => {
    // 发请求之前对整个表单进行校验
    await formRef.value.validate()
    let result = await reqAddOrUpdateTrademark(trademarkParams)
    if (result.code == 200) {
        dialogFormVisible.value = false
        ElMessage({ type: 'success', message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功' })
        getHasTrademark(trademarkParams.id ? pageNo.value : 1)
    } else {
        dialogFormVisible.value = false
        ElMessage({ type: 'error', message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败' })
    }
}
// 上传图片之前触发的钩子->约束文件类型和大小
const beforeAvatarUpload = (rawFile: any) => {
    if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 < 4) {
            return true
        } else {
            ElMessage({ type: 'error', message: '上传文件大小需要小于4M' })
            return false
        }
    } else {
        ElMessage({ type: 'error', message: '上传文件格式务必是图片格式' })
        return false
    }
}
// 上传图片成功的钩子
const handleAvatarSuccess = (response: any) => {
    trademarkParams.logoUrl = response.data
    formRef.value.clearValidate('logoUrl')
}

// 品牌名称自定义校验规则
const validatorTmName = (_: any, value: any, callBack: any) => {
    if (value.trim().length >= 2) {
        callBack()
    } else {
        callBack(new Error('品牌名称位数需要大于等于两位'))
    }
}
// 品牌logo自定义校验规则
const validatorLogoUrl = (_: any, value: any, callBack: any) => {
    if (value) {
        callBack()
    } else {
        callBack(new Error('LOGO图片务必上传'))
    }
}
// 表单校验规则
const rules = {
    tmName: [
        { required: true, trigger: 'blur', validator: validatorTmName }
    ],
    logoUrl: [
        { required: true, validator: validatorLogoUrl }
    ]
}
// 删除按钮气泡确认框的回调
const removeTradeMark = async (id: any) => {
    let result = await reqDeleteTrademark(id)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: '删除品牌成功' })
        getHasTrademark(trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
    } else {
        ElMessage({ type: 'error', message: '删除品牌失败' })
    }
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>